<?php

require_once "Zend/Tokenizer/Serialized/Abstract.php";
require_once "Zend/Json.php";

/**
 * @category   Zend
 * @package    Zend_Tokenizer
 * @copyright  Salomon BRYS
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Tokenizer_Serialized_JSON extends Zend_Tokenizer_Serialized_Abstract
{
	/**
	 * @var int
	 */
	protected $_objectDecodeType = Zend_Json::TYPE_ARRAY;

	/**
	 * Constructor
	 *
	 * @param Zend_Tokenizer_Interface $producer
	 */
	public function __construct(Zend_Tokenizer_Interface $producer, $objectDecodeType = Zend_Json::TYPE_ARRAY)
	{
		//TODO: Enhance Zend_Json, add an option so it returns the first json object parsed and does not fail if there is remaining data.
		//      So it will be possible to use reSerializeToGetLen to be much more optimized.
		parent::__construct($producer, false);
		$this->_objectDecodeType = $objectDecodeType;
	}

	final protected function unserialize($data, &$token)
	{
		try {
			$token = Zend_Json::decode($data, $this->_objectDecodeType);
			return true;
		} catch(Zend_Json_Exception $e) {
			return false;
		}
	}

	final protected function serialize($obj)
	{
		return Zend_Json::encode($obj);
	}
}
